package balmysundaycandy.more.low.level.urlfetch;

import com.google.appengine.api.urlfetch.URLFetchServicePb.URLFetchRequest;
import com.google.appengine.api.urlfetch.URLFetchServicePb.URLFetchResponse;
import com.google.appengine.repackaged.com.google.protobuf.AbstractMessage;
import com.google.appengine.repackaged.com.google.protobuf.InvalidProtocolBufferException;
import com.google.apphosting.api.ApiProxy;
import com.google.apphosting.api.ApiProxy.ApiProxyException;

abstract class UrlfetchOperation<Request extends AbstractMessage, Response extends AbstractMessage> {
	private static final String packageName = "urlfetch";

	public abstract Response call(Request request);

	public static final class FetchOperation extends UrlfetchOperation<URLFetchRequest, URLFetchResponse> {
		@Override
		public URLFetchResponse call(URLFetchRequest request) {
			URLFetchResponse.Builder response = URLFetchResponse.newBuilder();
			try {
				response.mergeFrom(ApiProxy.makeSyncCall(packageName, "Fetch", request.toByteArray()));
			} catch (InvalidProtocolBufferException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (ApiProxyException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return response.build();
		}
	}
}
